MUI 集成 nextjs

安装依赖包

首先确认安装了 next 和 MUI:

1npm install next react react-dom @mui/material @emotion/react @emotion/styled

然后安装 MUI 的 nextjs 兼容包:

1npm install @mui/material-nextjs @emotion/cache

配置

基本配置

编辑 app/layout.tsx,添加 APP Router:

1import { AppRouterCacheProvider } from '@mui/material-nextjs/v15-appRouter';
2
3export default function RootLayout(props) {
4    return (
5        <html lang="en">
6            <body>
7                <AppRouterCacheProvider>
8                    {props.children}
9                </AppRouterCacheProvider>
10            </body>
11        </html>
12    );
13}

主题配置

创建单独的 theme.ts 文件:

1'use client';
2import { blue, pink } from '@mui/material/colors';
3import { createTheme } from '@mui/material/styles';
4
5const theme = createTheme({
6    // 使用 CSS 主题变量,防止 SSR 闪烁
7    cssVariables: {
8        colorSchemeSelector: 'class'
9    },
10
11    // 颜色配置
12    colorSchemes: {
13        light: {
14            palette: {
15                primary: blue
16                secondary: pink,
17                mode: 'light',
18            },
19        },
20        dark: {
21            palette: {
22                primary: blue
23                secondary: pink,
24                mode: 'dark',
25            },
26        }
27    },
28
29    // 字体配置
30    typography: {
31        fontFamily: 'var(--font-roboto)',   
32    }, 
33});
34
35export default theme;

编辑 app/layout.tsx, 添加主题配置:

1import { AppRouterCacheProvider } from '@mui/material-nextjs/v15-appRouter';
2import { ThemeProvider } from "@mui/material";
3import InitColorSchemeScript from "@mui/material/InitColorSchemeScript";
4import theme from "theme";
5
6export default function RootLayout(props) {
7    return (
8        <html lang="en" suppressHydrationWarning>
9            <body>
10                <AppRouterCacheProvider>
11                    <ThemeProvider theme={theme}>
12                        <InitColorSchemeScript attribute="class" />
13                        {props.children}
14                    </ThemeProvider>
15                </AppRouterCacheProvider>
16            </body>
17        </html>
18    );
19}

使用 useColorScheme 来获取和操作主题:

1const {mode, setMode} = useColorScheme();

参考文档:https://mui.com/material-ui/integrations/nextjs/